import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
const service = axios.create({
    baseURL: 'test.com',
    headers: {
        get: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        post: {
        'Content-Type': 'application/json;charset=utf-8'
        }
    },
    timeout: 30000  
})

const protocolTool = (oldUrl: any) => { // 处理协议头//转为当前的协议
    return oldUrl.replace(/^\/\//, location.protocol + "//");
};
const requestUrlTool = (baseUrl: any, requestUrl: any) => {
    if (baseUrl.substr(-1,1) === "/" && requestUrl.substr(0,1) === "/") {
        return baseUrl + requestUrl.substr(1);
    } else if ((baseUrl.substr(-1,1) === "/" && requestUrl.substr(0,1) !== "/") || (baseUrl.substr(-1,1) !== "/" && requestUrl.substr(0,1) === "/")){
        return baseUrl + requestUrl;
    } else if (baseUrl.substr(-1,1) !== "/" && requestUrl.substr(0,1) !== "/") {
        return baseUrl + "/" + requestUrl;
    } else {
        return baseUrl + requestUrl;
    }
}
const api1 = 'api1';
const api2 = 'api2';
const api3 = 'api3';

axios.defaults.baseURL = protocolTool(axios.defaults.baseURL);

declare module 'axios' {
    export interface AxiosRequestConfig {
        type?: string;
    }
}

// 请求拦截器
service.interceptors.request.use((config: AxiosRequestConfig) => {
    if (config.type && config.type === 'api1') {
        config.url = requestUrlTool(api1, config.url);
    } else if (config.type && config.type === 'api2'){
        config.url = requestUrlTool(api2, config.url);
    } else if (config.type && config.type === "api3") {
        config.url = requestUrlTool(api3, config.url);
    } else {
        config.url = requestUrlTool(axios.defaults.baseURL, config.url);
    }
    return config
}, (error) => {
    return Promise.resolve(error)
})

// 响应拦截器
service.interceptors.response.use((response: AxiosResponse) => {
    return response
}, (error) => {
    return Promise.reject(error)
})

/**
 * 导出get请求方法
 * @url 请求地址
 * @params get请求参数
 */
export function get(url: string, params: any): Promise<AxiosResponse> | Promise<AxiosResponse<any>> {
    return new Promise((resolve, reject) => {
        service.get(url, {
            params: params
        }).then((res) => {
            resolve(res.data)
        }).catch((err) => {
            reject(err)
        })
    })
}


/**
 * 导出post请求方法
 * @url 请求地址
 * @params post请求参数
 */

export function post(url: string, params: any): Promise<AxiosResponse> | Promise<AxiosResponse<any>> {
    return new Promise((resolve, reject) => {
        service.post(url, params).then((res) => {
            resolve(res.data)
        }).catch((err) => {
            reject(err)
        })
    })
}
